/*
 * @File    :   python.js
 * @Time    :   2024/03/11 10:07:40
 * @Author  :   chakcy
 * @Email   :   947105045@qq.com
 * @description   :   运行python代码
 */

const { PythonShell } = require('python-shell')
const path = require('path')
const { encode, decode } = require('../base64')
const { basePath } = require('../../config')

// 执行方法
function runPythonScript(scriptPath, args) {
    return new Promise((resolve, reject) => {
        encodedArgs = encode(args)
        // 设置python脚本配置
        const options = {
            pythonPath: path.join(basePath, '../../python/python.exe'),
            pythonOptions: ['-u'],
            args: [encodedArgs]
        }
        // 执行脚本
        const pythonShell = new PythonShell(scriptPath, options)
        let error = null
        let result = ''
        // 监听message，获取输出
        pythonShell.on('message', (message) => {
            result += message
        })
        // 监听error，获取错误信息
        pythonShell.on('error', (err) => {
            error = err
        })
        // 监听end，脚本执行完成
        pythonShell.end((err) => {
            if (err) {
                reject(err)
            } else if (error) {
                reject(error)
            } else {
                if (JSON.parse(decode(result))) {
                    result = JSON.parse(decode(result))
                } else {
                    result = decode(result)
                }
                resolve(result)
            }
        })
    })
}

function runAllScripts(data) {
    if (!Array.isArray(data) || data.some(item => typeof item.scriptPath !== 'string' || typeof item.args !== 'object')) {
        return Promise.reject(new Error('Invalid input. Expecting an array of objects with path and args properties.'));
    }
    return Promise.all(
        data.map((item) => runPythonScript(item["scriptPath"], item["args"]))
    ).then(results => {
        return results
    }).catch(error => {
        console.error('An error occurred:', error)
        return null
    })
}

// 多脚本执行
module.exports = {
    runAllScripts
}

